package com.msc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msc.common.lang.dto.QqUserDTO;
import com.msc.entity.User;
import com.msc.common.lang.exception.CiliciliErrorCodeEnum;
import com.msc.common.lang.exception.CiliciliException;
import com.msc.service.AccountService;
import com.msc.service.UserService;
import com.msc.service.bo.UserInfoBo;
import com.msc.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author masc
 * @date 2022/6/18 8:43
 * <p></p>
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;


    @Override
    public UserInfoBo getUserInfoByQQOpenId(QqUserDTO qqUser, String qqOpenId, String qState) {
        User user = userService.getOne(new QueryWrapper<User>().eq("qq_openid", qqOpenId));
   /*     Assert.notNull(user, "用户名或密码错误");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("用户名或密码错误！");
        }*/
        if (user == null) {
            user = new User();
            user.setUsername(qqOpenId);
            user.setPassword("");
            user.setEmail("username@qq.com");
            user.setQqOpenid(qqOpenId);
            user.setNickname(qqUser.getNickname());
            user.setAvatar(qqUser.getFigureurl_qq());
            user.setUpdateTime(LocalDateTime.now());
            user.setCreateTime(LocalDateTime.now());
            user.setStatus(1);
            user.setRole("role_guest");
            userService.saveOrUpdate(user);
        }
        if (user.getStatus() == 0) {
            throw new CiliciliException(CiliciliErrorCodeEnum.USER_ID_NOT_STATUS);
        }
//        String jwt = jwtUtils.generateToken(user.getId(), user.getUsername());
        String jwt = jwtUtils.generateToken(user.getId(), user.getUsername());
        UserInfoBo userInfoBo = new UserInfoBo();
        userInfoBo.setAvatar(user.getAvatar());
        userInfoBo.setEmail(user.getEmail());
        userInfoBo.setNickname(user.getNickname());
        userInfoBo.setRole(user.getRole());
        userInfoBo.setJwt(jwt);
        userInfoBo.setUsername(user.getUsername());
        return userInfoBo;
    }
}
